const { verifyToken } = require('../config/jwt')
const db = require('../config/database')

const auth = async (req, res, next) => {
  try {
    const token = req.header('Authorization')?.replace('Bearer ', '')

    if (!token) {
      return res.status(401).json({ message: '未提供认证令牌' })
    }

    const decoded = verifyToken(token)

    // 验证用户是否存在
    const [users] = await db.execute(
      'SELECT id, username, name, email, role FROM users WHERE id = ?',
      [decoded.id]
    )

    if (users.length === 0) {
      return res.status(401).json({ message: '用户不存在' })
    }

    req.user = users[0]
    next()
  } catch (error) {
    if (error.name === 'TokenExpiredError') {
      return res.status(401).json({ message: '令牌已过期' })
    }
    return res.status(401).json({ message: '无效的令牌' })
  }
}

const requireRole = (roles) => {
  return (req, res, next) => {
    if (!roles.includes(req.user.role)) {
      return res.status(403).json({ message: '权限不足' })
    }
    next()
  }
}

module.exports = { auth, requireRole }
